// Package config 配置加载处理包
package config

import (
	"fmt"
	"organoid_public/infrastructure/config/model"
	"organoid_public/infrastructure/db"
	"os"
	"path/filepath"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

// Config 项目配置
type Config struct {
	Db    map[db.Name]db.Database `json:"db" yaml:"db"`
	App   *model.App              `json:"app" yaml:"app"`
	Token *model.Token            `json:"token" yaml:"token"`
}

// LoadConfig 加载配置
func LoadConfig(confPath string) *Config {
	var conf Config
	// 初始化 Viper
	viper.SetConfigType("yaml")
	s, _ := os.Getwd()
	fmt.Printf("%s", s)
	files, err := os.ReadDir(confPath)
	if err != nil {
		panic("读取配置文件出错：" + err.Error())
	}

	for _, file := range files {
		if filepath.Ext(file.Name()) != ".yaml" && filepath.Ext(file.Name()) != ".yml" {
			continue
		}

		filePath := filepath.Join(confPath, file.Name())
		viper.SetConfigFile(filePath)
		if err := viper.ReadInConfig(); err != nil {
			panic(fmt.Errorf("failed to read config file %s: %s", filePath, err))
		}

		if err := viper.Unmarshal(&conf); err != nil {
			panic(fmt.Errorf("failed to unmarshal config file %s: %s", filePath, err))
		}
	}

	// 监听配置文件的更改
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
		if err := viper.Unmarshal(&conf); err != nil {
			fmt.Printf("failed to unmarshal config file: %s\n", err)
		}
		// 在配置文件更改时执行需要的操作
		// 例如重新加载配置或重新初始化应用程序等
	})

	// 成功加载配置文件
	return &conf
}
